<?php

/*
 * 		CRUD + FULLTEXT INDEX SEARCH
 *		table: item, database: zend
 */
class Catalog_AdminItemController extends Zend_Controller_Action
{
	
	/*
	 *		SET default layout 
	 */
	
	public function preDispatch()
	{
		$url = $this->getRequest()->getRequestUri();
		$this->_helper->layout()->setLayout('admin');
		
		// admin security
		if(!Zend_Auth::getInstance()->hasIdentity())
		{
			$session = new Zend_Session_Namespace('zend_auth');
			$session->requestURL = $url;
			$this->_redirect('/admin/login');
		}
	}
	
	/*
	 *		INDEX action 
	*/
	
	public function indexAction()
	{
		// paging, add filters and validator for get request
		
		$filters = array(
				// for sort
				'sort' => array('HtmlEntities', 'StripTags', 'StringTrim'),
				'dir' => array('HtmlEntities', 'StripTags', 'StringTrim'),
				// for pager
				'page' => array('HtmlEntities', 'StripTags', 'StringTrim'));
		
		$validators = array(
				// for sort
				'sort' => array('Alpha', array(
						'InArray', 'haystack' => array(
								'RecordID', 'Title', 'Denomination', 
								'CountryID', 'GradeID', 'Year'))
						),
				'dir' => array('Alpha', array(
						'InArray', 'haystack' => array('asc', 'desc'))
						),
				// for pager
				'page' => array('Int')
		);
		
		// set new filters for paging
		$input = new Zend_Filter_Input($filters, $validators);
		$input->setData($this->getRequest()->getParams());
						
		if ($input->isValid())
		{
			
			$query = Doctrine_Query::create()
				->from('Zend_Model_Item i')
				->leftJoin('i.Zend_Model_Grade g')
				->leftJoin('i.Zend_Model_Country c')
				->leftJoin('i.Zend_Model_Type t')
				->orderBy(sprintf('%s %s', $input->sort, $input->dir));
		
			$prePage = 4;
			$numPageLink = 5;
		
			// initial component paging
			$pager = new Doctrine_Pager($query, $input->page, $prePage);
			$result = $pager->execute(array(), Doctrine::HYDRATE_ARRAY);
		
			// initial layout for pager
			$pagerRange = new Doctrine_Pager_Range_Sliding(array('chunk' => $numPageLink), $pager);
		
			$pagerUrlBase = $this->view->url(array(), 'admin-catalog-index', 1)."/{%page}";
			$pagerLayout = new Doctrine_Pager_Layout($pager, $pagerRange, $pagerUrlBase);
		
			// set template link for page
			$pagerLayout->setTemplate('<a href={%url}>{%page}</a>');
			$pagerLayout->setSelectedTemplate('<span class="current">{%page}</span>');
			$pagerLayout->setSeparatorTemplate('&nbsp;');

			$this->view->records = $result;
			$this->view->pages = $pagerLayout->display(null, true);
		} 
		else  
		{
			throw new Zend_Controller_Action_Exception('Invalid input action index');
		}
	}
	
	/*
	 * 		DISPLAY action
	 */
	
	public function displayAction()
	{
		//validation
		$filters = array(
				'id' => array('HtmlEntities', 'StripTags', 'StringTrim')
		);
	
		$validators = array(
				'id' => array('NotEmpty', 'Int')
		);
	
		$input = new Zend_Filter_Input($filters, $validators);
		$input->setData($this->getRequest()->getParams());
	
		if($input->isValid())
		{
			$query = Doctrine_Query::create()
			->from('Zend_Model_Item i')
			->leftJoin('i.Zend_Model_Country c')
			->leftJoin('i.Zend_Model_Grade g')
			->leftJoin('i.Zend_Model_Type t')
			->where('i.RecordID = ?', $input->id);
			//->andWhere('i.DisplayStatus = 1')
			//->andWhere('i.DisplayUntil >= CURDATE()');
	
			$res = $query->fetchArray();
			if(count($res) == 1)
			{
				$this->view->item = $res[0];
				
				$this->view->images = array();
				$config = $this->getInvokeArg('bootstrap')->getOption('uploads');
				foreach (glob("{$config['uploadPath']}/{$this->view->item['RecordID']}_*") as $file)
				{
					$this->view->images[] = basename($file);
				}
			}
			else
			{
				throw new Zend_Controller_Action_Exception('dont work',404);
			}
		}
		else
		{
			throw new Zend_Controller_Action_Exception('invalid $_GET data');
		}
	}
	
	/*
	 *		DELETE action
	*/
	
	public function deleteAction()
	{
		// set filters
		$filters = array(
				'ids' => array('HtmlEntities', 'StripTags', 'StringTrim'));
		// set Validators
		$validators = array(
				'ids' => array('NotEmpty', 'Int'));
		
		$input = new Zend_Filter_Input($filters, $validators);
		$input->setData($this->getRequest()->getParams());
		
		if($input->isValid())
		{
			$query = Doctrine_Query::create()
					->delete('Zend_Model_Item i')
					->whereIn('i.RecordID', $input->ids);
			$result = $query->execute();
			
			$config = $this->getInvokeArg('bootstrap')->getOption('uploads');
			foreach ($input->ids as $id)
			{
				foreach (glob("{$config['uploadPath']}/{$id}_*") as $file)
				{
					unlink($file);
				}	
			}
			
			$this->_helper->getHelper('FlashMessenger')->addMessage('The record were successfully deleted');
			$this->_redirect('/admin/catalog/item/success');
		}
		else 
		{
			throw new Zend_Controller_Action_Exception('Invalid input');
		}		
	}
	
	/*
	 *		UPADTE table item 
	 */
	
	public function updateAction()
	{
		// to show update form
		$updateItemForm = new Inc_Form_ItemUpdate();
		$this->view->updateItemForm = $updateItemForm;
		
		
		// correcting date from xx-xx-xxxx in xxxx-xx-xx
		if ($this->getRequest()->isPost())
		{
			$postData = $this->getRequest()->getPost();
			$postData['DisplayUntil'] = sprintf('%04d-%02d-%02d', 
					$this->getRequest()->getPost('DisplayUntil_year'),
					$this->getRequest()->getPost('DisplayUntil_mount'),
					$this->getRequest()->getPost('DisplayUntil_day'));
						
		
		
			// if post
			if ($updateItemForm->isValid($postData))
				{
					$input = $updateItemForm->getValues();
					$this->view->arr = $input['RecordID'];
					$query = Doctrine::getTable('Zend_Model_Item')
						->find($input['RecordID']);
					$query->fromArray($input);
					$query->DisplayUntil = ($query->DisplayUntil == 0) ? null : $query->DisplayUntil;
					$query->save();
			
					$this->_helper->getHelper('FlashMessenger')->addMessage('The record upadted succesfully');
					$this->_redirect('/admin/catalog/item/success');
			 
				}
		}
		// if get
		else 
		{
			// set filters
			$filters = array(
					'id' => array('HtmlEntities', 'StripTags', 'StringTrim'));
			// set Validators
			$validators = array(
					'id' => array('NotEmpty', 'Int'));
			
			$input = new Zend_Filter_Input($filters, $validators);
			$input->setData($this->getRequest()->getParams());
			
			if($input->isValid())
			{
				$query = Doctrine_Query::create()
				->from('Zend_Model_Item i')
				->leftJoin('i.Zend_Model_Country c')
				->leftJoin('i.Zend_Model_Grade g')
				->leftJoin('i.Zend_Model_Type t')
				->where('i.RecordID = ?', $input->id);
				
				$result = $query->fetchArray();
			
				if (count($result)==1)
				{
					// correct list date
					$date = $result[0]['DisplayUntil'];
					
					$result[0]['DisplayUntil_day'] = date('d', strtotime($date));
					$result[0]['DisplayUntil_mount'] = date('m', strtotime($date));
					$result[0]['DisplayUntil_year'] = date('Y', strtotime($date));
					
					$this->view->updateItemForm->populate($result[0]);
				}
				else 
				{
					throw new Zend_Controller_Action_Exception('Paage not found', 404);
				}
			}
			else 
			{
					throw new Zend_Controller_Action_Exception('Invalid input');
			}
		}
		
	}
	
	/*
	 *		SUCCESS table item
	*/
	
	public function successAction()
	{
		if ($this->_helper->getHelper('FlashMessenger')->getMessages())
		{
			$this->view->message = $this->_helper->getHelper('FlashMessenger')->getMessages();
		}
		else 
		{
			$this->_redirect('/admin/catalog/item/index');	
		}
	}
	
	/*
	 *		CREATE INDEX FOR FULLTEXT SEARCH 
	 */
	
	public function createFulltextIndexAction()
	{
		// select all from table index
		$query = Doctrine_Query::create()
			->from('Zend_Model_Item i')
			->leftJoin('i.Zend_Model_Country c')
			->leftJoin('i.Zend_Model_Grade g')
			->leftJoin('i.Zend_Model_Type t')
			->where('i.DisplayStatus = 1');
			//->andWhere('i.DisplayUntil >= CURDATE()');
		
		$res = $query->fetchArray();
		
		$config = $this->getInvokeArg('bootstrap')->getOption('indexes');
		
		$index = Zend_Search_Lucene::create($config['indexPath']);
		foreach ($res as $r)
		{
			$doc = new Zend_Search_Lucene_Document();
			
			$doc->addField(Zend_Search_Lucene_Field::text('Title', $r['Title']));
			$doc->addField(Zend_Search_Lucene_Field::text('Title', $r['Title']));
			$doc->addField(Zend_Search_Lucene_Field::text('Country', 
					$r['Zend_Model_Country']['CountryName']));
			$doc->addField(Zend_Search_Lucene_Field::text('Grade', 
					$r['Zend_Model_Grade']['GradeName']));
			$doc->addField(Zend_Search_Lucene_Field::text('Year', $r['Year']));
			
			$doc->addField(Zend_Search_Lucene_Field::unStored('Description', $r['Description']));
			$doc->addField(Zend_Search_Lucene_Field::unStored('Denomination', $r['Denomination']));
			$doc->addField(Zend_Search_Lucene_Field::unStored('Type', $r['Zend_Model_Type']['TypeName']));
			
			$doc->addField(Zend_Search_Lucene_Field::unIndexed('SalePriceMin', $r['SalePriceMin']));
			$doc->addField(Zend_Search_Lucene_Field::unIndexed('SalePriceMax', $r['SalePriceMax']));
			$doc->addField(Zend_Search_Lucene_Field::unIndexed('RecordID', $r['RecordID']));
			
			$index->addDocument($doc);
		}
		
		$count = $index->count();
		$this->_helper->getHelper('FlashMessenger')->addMessage("The index was succerfully created 
				with {$count} documents.");
		$this->_redirect('/admin/catalog/item/success');
	}
}